import { Form, Input, Button, Checkbox } from 'antd';
import { UserOutlined, LockOutlined, EyeTwoTone, EyeInvisibleOutlined } from '@ant-design/icons';
import { login } from "@/api/service/userService"
import { message } from "antd";
import { useNavigate, Link } from 'react-router-dom';
import { useDispatch } from 'react-redux'
import { changeUserInfo,setToken} from "@/store/modules/userSlice"
import { useEffect} from 'react';

const bg = {
  display: 'flex',
  justifyContent: 'center',
  alignItems: 'center',
  height: '100vh',
  backgroundImage: 'linear-gradient(to right, #9fe1fa, #f4edc9)'
}

const login_card = {
  width: '400px',
  padding: '24px',
  backgroundColor: 'white',
  borderRadius: '8px',
  boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)'
}

export default function Login() {
  const [form] = Form.useForm()
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate()
  const dispatch = useDispatch()
  const iconRender = (visible: Boolean) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)

  useEffect(()=>{
    const savedUsername=localStorage.getItem('username')
    const savedPassword=localStorage.getItem('password')

    if(savedUsername && savedPassword){
      form.setFieldsValue({
        username:savedUsername,
        password:savedPassword,
        remember:true
      })
    }
  },[form]);

  
  const onFinish = (values: any) => {
    console.log(values);

    // 进行接口请求
    login(values).then(val => {
      console.log('登录参数为：',val);
      // 提交同步action进行token和用户信息保存
      dispatch(changeUserInfo(val))
      dispatch(setToken(val.token))
      // 登录成功给提示信息
      messageApi.open({
        type: 'success',
        content: '登录成功！',
      }).then(() => {
      // 用户选择记住我
      if(values.remember){
        localStorage.setItem('username',values.username || '')
        localStorage.setItem('password',values.password || '')
      }else{
        localStorage.removeItem('username');
        localStorage.removeItem('password');
      }
        navigate("/workbench")
      });
    }).catch(err => {
      // 登录失败给提示信息
      
      messageApi.open({
        type: 'error',
        content: err.message,
      });

    })
  };

  return (
    <div style={bg}>
      {/* 提示框 */}
      {contextHolder}
      <div style={login_card}>
        <h2 style={{ textAlign: 'center' }}>欢迎登录</h2>
        <Form
          name="login"
          onFinish={onFinish}
          form={form}  
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '用户名不能为空!' },
            { pattern: /^[a-zA-Z][a-zA-Z0-9_-]{5,19}$/, message: '6至20位，以字母开头，允许字母、数字、减号、下划线' }]}
            hasFeedback
          >
            <Input prefix={<UserOutlined />} placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码!' },
              { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,20}$/, message: '6至20位，包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符(包括@$!%*?&)' }
            ]}
            hasFeedback
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请输入密码"
              iconRender={iconRender}
            />
          </Form.Item>
          <Form.Item>
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>记住我</Checkbox>
            </Form.Item>
            <Link to="/reset" style={{ float: 'right' }}>
              忘记密码
            </Link>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
              立即登录
            </Button>
          </Form.Item>
        </Form>
        <div style={{ textAlign: 'center' }}>
          还没有账号？<Link to="/register">立即注册</Link>
        </div>
      </div>
    </div>
  )
}




